<template>
  <el-dialog
    :close-on-click-modal="false"
    :title="title"
    :visible.sync="dialogFormVisible"
    width="900px"
    @close="close"
  >
    <template>
      <el-form ref="form" label-width="100px" :model="form" :rules="rules" :disabled="disabled">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="选择类型" prop="types">
              <el-select filterable clearable v-model="form.mold_id" @change="handleChange" style="width: 100%">
                <el-option :value="item.id" v-for="(item,key) in mold_list" :key="key" :label="item.name"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="类型说明">
              <el-input v-model="form.remark" placeholder="类型说明" readonly/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="SKU名称" prop="attribute_name_label">
              <el-input v-model="form.attribute_name_label" placeholder="SKU名称" :readonly="form.input_type === 1"
                        clearable/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="SKU规格" prop="attribute_spec_label">
              <el-input v-model="form.attribute_spec_label" placeholder="SKU规格" :readonly="form.input_type === 1"
                        clearable/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="名称" v-if="form.input_type === 1">
          <el-table
            :data="form.attribute_name"
            border
          >
            <el-table-column
              align="center"
              label="属性名称"
              show-overflow-tooltip
            >
              <template slot-scope="scope">
                {{ scope.row.name }}<span v-if="scope.row.input_type === 5">(%)</span>
              </template>
            </el-table-column>
            <el-table-column
              align="center"
              label="具体内容"
            >
              <template slot-scope="scope">
                <el-input v-if="scope.row.input_type === 1" v-model="scope.row.value" placeholder="请输入内容"
                          @input="attributeReName" clearable/>
                <el-select v-else-if="scope.row.input_type === 2" v-model="scope.row.value" @change="attributeReName"
                           clearable filterable>
                  <el-option v-for="item in scope.row.object" :key="item.id" :value="item.name"></el-option>
                </el-select>
                <el-date-picker v-else-if="scope.row.input_type === 3" v-model="scope.row.value"
                                placeholder="请输入日期" clearable
                                type="date" format="yyyy-MM-dd" value-format="yyyy-MM-dd"
                                @input="attributeReName"/>
                <el-input-number v-else-if="scope.row.input_type === 4" v-model="scope.row.value" :step="1"
                                 placeholder="请输入" @input="attributeReName"/>
                <el-input-number v-else-if="scope.row.input_type === 5" v-model="scope.row.value" :precision="2"
                                 :step="0.01" :max="100" :min="0" @input="attributeReName"/>
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>
        <el-form-item label="SKU规格属性" v-if="form.input_type === 1">
          <el-table
            :data="form.attribute_spec"
            border
          >
            <el-table-column
              align="center"
              label="属性名称"
              show-overflow-tooltip
            >
              <template slot-scope="scope">
                {{ scope.row.name }}<span v-if="scope.row.input_type === 5">(%)</span>
              </template>
            </el-table-column>
            <el-table-column
              align="center"
              label="具体内容"
            >
              <template slot-scope="scope">
                <el-input v-if="scope.row.input_type === 1" v-model="scope.row.value" placeholder="请输入内容" clearable
                          @input="attributeReSpec"/>
                <el-select v-else-if="scope.row.input_type === 2" v-model="scope.row.value" @change="attributeReSpec"
                           clearable filterable>
                  <el-option v-for="(item, key) in scope.row.object" :key="key" :value="item.name"></el-option>
                </el-select>
                <el-date-picker v-else-if="scope.row.input_type === 3" v-model="scope.row.value"
                                placeholder="请输入日期" clearable
                                type="date" format="yyyy-MM-dd" value-format="yyyy-MM-dd"
                                @input="attributeReSpec"/>
                <el-input-number v-else-if="scope.row.input_type === 4" v-model="scope.row.value" :step="1"
                                 placeholder="请输入" @input="attributeReSpec"/>
                <el-input-number v-else-if="scope.row.input_type === 5" v-model="scope.row.value" :precision="2"
                                 :step="0.01" :max="100" :min="0" @input="attributeReSpec"/>
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>
        <el-form-item label="上传附件">
          <template v-if="form.file_path">
            <el-link :href="fileRootPath+form.file_path" :underline="false"
                     :download="form.file_path">
              <el-button icon="el-icon-download" size="small" type="success" plain>下载</el-button>
            </el-link>
            <el-link :underline="false">
              <el-button @click="delete_file" icon="el-icon-delete" type="danger" plain>删除</el-button>
            </el-link>
          </template>
          <template v-else>
            <attachment-upload typ="sku_file" @input="changeUrlFile" ref="uploadFile"/>
          </template>
        </el-form-item>
        <el-form-item label="SKU图片" style="height:180px;margin-bottom: 30px">
          <template v-if="form.pic_path">
            <el-col>
              <el-image :src="fileRootPath+form.pic_path" style="width:auto;height:180px"/>
            </el-col>

            <el-col>
              <el-button @click="delete_pic" icon="el-icon-delete">删除图片</el-button>
            </el-col>
          </template>
          <template v-else>
            <Upload ref="uploadPic" typ="sku" @input="changeUrl"/>
            <p class="tips-words">ps：建议上传jpeg/jpg/png文件，且不超过10M</p>
          </template>
        </el-form-item>
      </el-form>
    </template>
    <template #footer>
      <el-button @click="close">取 消</el-button>
      <el-button type="primary" :disabled="disabled" @click="save">确 定</el-button>
    </template>
  </el-dialog>
</template>

<script>
import {getList, getPinYin, detailCateories} from '@/api/sku/mold'
import {doEdit} from '@/api/sku/classify'
import {getAdminListByRole} from "@/api/manage/adminUser";
import Upload from '@/views/other/upload/SingleImage3'
import AttachmentUpload from "@/views/other/upload/attachment";

export default {
  watch: {
    '$route'(to, from) {
      // 路由变化时重新加载数据
      if (to.path === '/sku/classify') {
        // 路由变化为当前页时重新加载数据
        this.handleQueryss()
        this.attributeReName()
      }
    }
  },
  name: 'customerEdit',
  components: {Upload, AttachmentUpload},
  data() {
    return {
      disabled: false,
      form: {
        label: '',
        attribute_name_label: '',
        attribute_spec_label: '',
        code: '',
        sku_mold_id: [],
        attribute_spec: [],
        attribute_name: [],
        stock_attribute: [],
        remark: '',
        skuMold: {},
      },
      rules: {
        code: [
          {required: true, trigger: 'blur', message: '请填写编码'},
        ],
        name: [
          {required: true, trigger: 'blur', message: '请填写属性规格'},
        ],
      },
      title: '',
      dialogFormVisible: false,
      mold_list: [],
      fileRootPath: process.env.VUE_APP_FILE_ROOT_PATH

    }
  },
  created() {
    this.handleQueryss()
    this.attributeReName()
  },
  methods: {
    attributeReName() {
      this.form.attribute_name_label = '';
      this.form.attribute_name.forEach((item) => {
        if (item && item.value) {
          this.form.attribute_name_label += item.value + '/';
          const index = this.form.attribute_spec.findIndex(sepcItem => sepcItem.id === item.id);
          if (index !== -1) {
            this.$set(this.form.attribute_spec, index, item);
          }
        }
      });
      this.attributeReSpec()
    },
    attributeReSpec() {
      this.form.attribute_spec_label = '';
      this.form.attribute_spec.forEach((item) => {
          if (item && item.value)  {
            this.form.attribute_spec_label += item.value + '/';
          }
      });
      const kwh = this.form.attribute_spec.find(kwhItem => kwhItem.name === '标称能量KWH');
      const ah = this.form.attribute_spec.find(ahItem => ahItem.name === '标准容量Ah');
      const v = this.form.attribute_spec.find(vItem => vItem.name === '标准电压V');
      if (kwh && ah && v)
        kwh.value = ah.value*v.value/1000
    },
    changeUrlFile(data) {
      this.form.tempPath_file = data.tempPath
      this.form.fileType_file = data.fileType
    },
    changeUrl(data) {
      this.form.tempPath = data.tempPath
      this.form.fileType = data.fileType
    },
    handleChange() {
      detailCateories({id: this.form.mold_id, 'production_attribute': 1}).then((response) => {

        //查询属性和名称，是否原来就存在，并且赋值
        this.form.attribute_name.forEach((name) => {
          const foundItem = response.data.attrNameList.find(item => item.id === name.id);
          if (foundItem) {
            foundItem.value = name.value;
          }
        });
        this.form.attribute_spec.forEach((name) => {
          const foundItem = response.data.attrSpecList.find(item => item.id === name.id);
          if (foundItem) {
            foundItem.value = name.value;
          }
        });
        this.form.attribute_name = response.data.attrNameList
        this.form.attribute_spec = response.data.attrSpecList
        this.form.input_type = response.data.input_type
        this.form.skuMold.name = response.data.name
        this.form.remark = response.data.remark
      })
    },
    handleQueryss() {
      getList({'pageNo': 'all'}).then(({data}) => {
        this.mold_list = data.list;
      });
    },
    delete_pic() {
      this.form.pic_path = ''
    },
    delete_file() {
      this.form.file_path = ''
    },
    pinyin() {
      getPinYin({'name': this.form.name}).then(response => {
        this.form.code = response.data.code
      })
    },
    forceUpdate() {
      this.$forceUpdate()
    },
    showEdit(row) {
      if (!row) {
        this.title = '添加'
        this.form.temp_old = ''
        this.form.temp_old_file = ''

      } else {
        this.title = '编辑'
        this.form = Object.assign({}, row)
        this.form.temp_old = this.form.pic_path
        this.form.temp_old_file = this.form.file_path
        this.handleChange()

      }
      this.dialogFormVisible = true
      this.disabled = false
    },
    viewEdit(row) {
      this.title = '查看'
      this.form = Object.assign({}, row)
      this.dialogFormVisible = true
      this.disabled = true

    },
    close() {
      this.$refs['form'].resetFields()
      if (this.$refs['uploadPic'])
        this.$refs['uploadPic'].resetTempUrl()
      this.form = this.$options.data().form
      this.dialogFormVisible = false
    },
    save() {
      this.$refs['form'].validate(async (valid) => {
        if (valid) {
          this.form.attribute_name.forEach(item => {
            delete item.object; // 删除 object 键
          });

          this.form.attribute_spec.forEach(item => {
            delete item.object; // 删除 object 键
          });
          const {msg} = await doEdit(this.form)
          this.$baseMessage(msg, 'success', 'vab-hey-message-success')
          this.$emit('fetch-data')
          this.close()
        }
      })
    },
  }
  ,
}
</script>
<style scoped>
.row-with-margin {
  margin-bottom: 5px; /* 你可以根据需要调整这个值 */
}

.gap {
  /* 如果你已经有了gap类，确保它不会影响布局 */
}
</style>
